//
//  LXRCommentViewController.m
//  01- 百思不得姐
//
//  Created by mac on 16/6/28.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "LXRCommentViewController.h"
#import "LXRTopicCell.h"
#import "LXRTopicModel.h"
#import "LXRCommentModel.h"
#import "LXRCommentHeaderView.h"
#import "LXRCommectCell.h"


#import "MJExtension.h"
#import "MJRefresh.h"
#import "LXRHTTPSessionManager.h"

//Cell标识
static NSString* const LXRCommectCellId = @"comment";

@interface LXRCommentViewController ()<UITableViewDataSource,UITableViewDelegate>
/** 工具条底部间距*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttomSpace;
/**评论内容tableView*/
@property (weak, nonatomic) IBOutlet UITableView *tableView;

/************服务器返回的数据*************/
/** 最热 评论数据*/
@property(nonatomic,strong)NSArray* hotComment;
/** 最新 评论数据*/
@property(nonatomic,strong)NSMutableArray* latestComment;

/************临时数据*************/
/**临时存top_cmt数据*/
@property(nonatomic,strong)NSArray* saved_top_cmt;
/**临时页码*/
@property(nonatomic,assign)NSInteger page;
/**临时请求*/
@property(nonatomic,strong)LXRHTTPSessionManager* manager;

@end

@implementation LXRCommentViewController

-(AFHTTPSessionManager *)manager{
    
    if (_manager == nil) {
        _manager = [LXRHTTPSessionManager manager];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    /**基本设置*/
    [self setupBasic];
    
    /**设置头部视图*/
    [self setupHeader];
    
    /**添加刷新控件*/
    [self setupRefresh];
    
}
/**添加刷新控件*/
-(void)setupRefresh{
    //头部刷新控件
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(LoadNewComment)];
    
    [self.tableView.mj_header beginRefreshing];
    
    //尾部刷新控件
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(LoadMoreCemment)];
    //隐藏尾部刷新控件
    self.tableView.mj_footer.hidden = YES;
}

/**加载新数据*/
-(void)LoadNewComment{
    //结束之前的所有请求   tasks参数里包含所有请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    //请求参数
    NSMutableDictionary* prams = [NSMutableDictionary dictionary];
    prams[@"a"] = @"dataList";
    prams[@"c"] = @"comment";
    prams[@"data_id"] = self.model.ID;
    prams[@"hot"] = @"1";
    
    
    LXRWeakSelf;
    //网络请求
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:prams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //如果不是字典返回,根据新帖控制器
        if(![responseObject isKindOfClass:[NSDictionary class]]) return ;
        
        //最热评论
        weakSelf.hotComment = [LXRCommentModel mj_objectArrayWithKeyValuesArray:responseObject[@"hot"]];
        
        //最新评论
        weakSelf.latestComment = [LXRCommentModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        //返回第一页数据
        weakSelf.page = 1;
        
        //刷新表格
        [weakSelf.tableView reloadData];
        //结束头部刷新
        [weakSelf.tableView.mj_header endRefreshing];
        
        //控制footer的状态
        NSInteger total = [responseObject[@"total"] integerValue];
        if (weakSelf.latestComment.count>=total) { //当评论数大于等于服务器传回评论总数时,已加载全部
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //结束头部刷新
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    
    
}

/**加载更多数据*/
-(void)LoadMoreCemment{
    //结束之前的所有请求  tasks参数里包含所有请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    
    NSInteger page = self.page + 1;
    
    //请求参数
    NSMutableDictionary* prams = [NSMutableDictionary dictionary];
    prams[@"a"] = @"dataList";
    prams[@"c"] = @"comment";
    prams[@"data_id"] = self.model.ID;
    prams[@"page"] = @(page);
    //最后评论人ID  进行比较
    LXRCommentModel* model = [self.latestComment lastObject];
    prams[@"lastcid"] = model.ID;
    
    LXRWeakSelf;
    //网络请求
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:prams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //如果不是字典返回,根据新帖控制器
        if(![responseObject isKindOfClass:[NSDictionary class]]) {
            
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            return ;
        }
        
        //最新评论
        NSArray* newComments = [LXRCommentModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        //将新评论加到评论数组中
        [weakSelf.latestComment addObjectsFromArray:newComments];
        
    
        //请求成功page赋值
        weakSelf.page = page;
        
        //刷新表格
        [weakSelf.tableView reloadData];
        
        //控制footer的状态
        NSInteger total = [responseObject[@"total"] integerValue];
        if (weakSelf.latestComment.count>=total) { //当评论数大于等于服务器传回评论总数时,已加载全部
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }else {
            //结束尾部刷新
            [weakSelf.tableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //结束尾部刷新
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}
/**设置头部视图*/
-(void)setupHeader{
    //创建header  再次包装头部视图
    UIView* header = [[UIView alloc]init];
    
    //如果有最热评论
    if (self.model.top_cmt.count) {
        self.saved_top_cmt = self.model.top_cmt;          //将数据给临时数组
        self.model.top_cmt = nil;                         //清空模型数据
        [self.model setValue:@0 forKeyPath:@"cellHeight"];//通过KVC对cellHeight重新赋值
    }
    
    //添加cell
    LXRTopicCell* cell = [LXRTopicCell viewFromXib];
    cell.model = self.model;
    cell.size = CGSizeMake(LXRScreenW, self.model.cellHeight);
    [header addSubview:cell];
    //header的高度
    header.height = self.model.cellHeight + LXRTopicCellMargin;
    //设置header
    self.tableView.tableHeaderView = header;

}

/**基本设置*/
-(void)setupBasic{
    
    //设置导航条标题
    self.title = @"评论";
    
    //设置背景
    self.tableView.backgroundColor = LXR_BJ_Color;
    
    //去掉Cell分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //添加导航条右边按钮
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"comment_nav_item_share_icon" highImage:@"comment_nav_item_share_icon_click" target:nil action:nil];
    
    //监听键盘弹出通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    //注册Cell
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRCommectCell class]) bundle:nil] forCellReuseIdentifier:LXRCommectCellId];
    
    /***重点:cell的高度高度  (IOS8版本以后可以自动设置Cell的高度)****/
    //估计高度
    self.tableView.estimatedRowHeight = 44;
    //系统自带自动根据估计高度计算Cell合适的高度
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    
    
}

#pragma mark - 数据源
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSInteger hotCount = self.hotComment.count;
    NSInteger latestCount = self.latestComment.count;
    
    if (hotCount) return 2;     //有最热评论数据
    if (latestCount) return 1;  //有最新评论数据
    return 0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSInteger hotCount = self.hotComment.count;
    NSInteger latestCount = self.latestComment.count;
    
    //判断是否隐藏尾部刷新控件
    tableView.mj_footer.hidden = (latestCount == 0);
    
    if (section == 0){
        //如果第0组有最热评论就返回最热评论数量,没有就返回最新评论数量
        return hotCount ? hotCount : latestCount;
    }
    //非第0组 返回最新评论数量
    return latestCount;
}

/**返回第Section组的所有评论数据*/
-(NSArray*)commentsInSection:(NSInteger)section{
    NSInteger hotCount = self.hotComment.count;
    if(section == 0){
        return hotCount?self.hotComment:self.latestComment;
    }
    return self.latestComment;
}
/**返回每一行的模型数据*/
-(LXRCommentModel*)commentInIndexPath:(NSIndexPath*)indexPath{
    return [self commentsInSection:indexPath.section][indexPath.row];
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LXRCommectCell* cell = [tableView dequeueReusableCellWithIdentifier:LXRCommectCellId];
    
    cell.model = [self commentInIndexPath:indexPath];
    
    
    return cell;
}

/**每组头标题*/
/**第二种实现头部标题*/
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    LXRCommentHeaderView* header = [LXRCommentHeaderView headerViewWithTableView:tableView];
    
    //设置Lable数据
    NSInteger hotCount = self.hotComment.count;
    if (section == 0) {
        header.title = hotCount?@"最热评论":@"最新评论";
    }else{
        header.title = @"最新评论";
    }
    
    return header;
}


#pragma mark  - 键盘处理
/** 计算键盘Frame,约束改变*/
-(void)keyboardWillChangeFrame:(NSNotification*)note{
    //键盘显示\隐藏完毕的frame
    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //修改底部约束  根据键盘的Y值来修改约束值
    self.buttomSpace.constant = LXRScreenH - frame.origin.y;
    //键盘弹出动画时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
        //强制布局
        [self.view layoutIfNeeded];
    }];
}
#pragma mark  UITableViewDelegate代理方法
/**监听当拖动时  --->不需要调用实现方法特别频的代理方法*/
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //退出键盘
    [self.view endEditing:YES];
    //动画退出菜单
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
}

/**选中某行,弹出 UIMenuController 菜单*/
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //拿到共享的菜单Menu
    UIMenuController* menu = [UIMenuController sharedMenuController];
    //当点击同一行cell菜单消失
    if (menu.isMenuVisible) {
        [menu setMenuVisible:NO animated:YES];
        return;
    }
    
    //被点击的cell
    LXRCommectCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    //点击cell成为第一响应者
    [cell becomeFirstResponder];

    //自定义添加UIMenuItem
    UIMenuItem* ding = [[UIMenuItem alloc]initWithTitle:@"顶" action:@selector(ding:)];
    UIMenuItem* replay = [[UIMenuItem alloc]initWithTitle:@"回复" action:@selector(replay:)];
    UIMenuItem* report = [[UIMenuItem alloc]initWithTitle:@"举报" action:@selector(report:)];
    //添加到菜单中
    menu.menuItems = @[ding,replay,report];
    //菜单弹出位置 在cell的bounds范围
    CGRect rect = CGRectMake(0, cell.height*0.5, cell.width, cell.height*0.5);
    [menu setTargetRect:rect inView:cell];
    //动画显示菜单
    [menu setMenuVisible:YES animated:YES];
}
#pragma mark - MenuItem点击处理
-(void)ding:(UIMenuController*)menu
{
    LXRLogFunc;
    //找出选中的行号
    NSIndexPath* selectPath = [self.tableView indexPathForSelectedRow];
    //打印选中cell的评论内容
    LXRLog(@"%@",[self commentInIndexPath:selectPath].content);
}
-(void)replay:(UIMenuController*)menu
{
    LXRLogFunc;
    //找出选中的行号
    NSIndexPath* selectPath = [self.tableView indexPathForSelectedRow];
    //打印选中cell的评论内容
    LXRLog(@"%@",[self commentInIndexPath:selectPath].content);
}
-(void)report:(UIMenuController*)menu
{
    LXRLogFunc;
    //找出选中的行号
    NSIndexPath* selectPath = [self.tableView indexPathForSelectedRow];
    //打印选中cell的评论内容
    LXRLog(@"%@",[self commentInIndexPath:selectPath].content);
}

/**释放*/
-(void)dealloc{
    //释放通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    //恢复帖子的top_cmt
    if (self.saved_top_cmt.count) {//如果临时数据有值
        self.model.top_cmt = self.saved_top_cmt;
        [self.model setValue:@0 forKeyPath:@"cellHeight"];
    }
    //取消所有任务
    //[self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    [self.manager invalidateSessionCancelingTasks:YES];
}
@end
